package en.edu.lzzy.bookmanagement.service;

import en.edu.lzzy.bookmanagement.repository.BookRepository;
import en.edu.lzzy.bookmanagement.repository.CategoryRepository;
import en.edu.lzzy.bookmanagement.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import en.edu.lzzy.bookmanagement.model.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookRepository bookRepository;

    @Override
    // 从数据库中获取所有图书的列表
    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    @Override
    // 将图书对象保存到数据库中
    public void saveBook(Book book) {
        bookRepository.save(book);
    }

    @Override
    // 根据id查找并返回对应的图书对象。如果找不到对应的图书，则返回`null`
    public Book getBookById(long id) {
        return bookRepository.findById(id).orElse(null);
    }

    @Override
    // 根据id从数据库中删除对应的图书
    public void deleteBookById(long id) {
        bookRepository.deleteById(id);
    }

    @Override
    // 在数据库中根据标题或作者进行模糊查找，并返回一个分页的结果
    public Page<Book> searchBooks(String keyword, String searchBy, Pageable pageable) {
        switch (searchBy) {
            case "title":
                return bookRepository.findByTitleContaining(keyword, pageable);
            case "author":
                return bookRepository.findByAuthorContaining(keyword, pageable);
            default:
                throw new IllegalArgumentException("Invalid searchBy parameter");
        }
    }

    // 分页查询图书列表
    @Override
    public Page<Book> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        Sort sort = sortDirection.equals("asc") ? Sort.by(sortField).ascending() : Sort.by(sortField).descending();
        PageRequest pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return bookRepository.findAll(pageable);
    }
}